#define _USE_MATH_DEFINES
#include <stdio.h>
#include <math.h>
#include <SDL2/SDL.h>

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
#define BALL_RADIUS 10
#define ARC(angle) ((angle) * (M_PI / 180))

int main(int argc,char** argv) {
    // 初始化 SDL
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
        return 1;
    }

    // 创建窗口和渲染器
    SDL_Window *window = SDL_CreateWindow("Sin Wave", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0);
    if (!window) {
        printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if (!renderer) {
        printf("Renderer could not be created! SDL_Error: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 1;
    }

    // 主循环变量
    int running = 1;
    SDL_Event event;
    int ball_x = BALL_RADIUS;
    int ball_y = SCREEN_HEIGHT / 2;

    // 主循环
    while (running) {
        // 处理事件
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = 0;
            }
        }

        // 清除屏幕（设置为黑色）
        SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
        SDL_RenderClear(renderer);

        // 更新小球位置
        ball_x += 10;
        ball_y = (int)(SCREEN_HEIGHT / 2 * (1 + sin(ARC(ball_x))));

        // 渲染小球（设置为白色）
        SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
        SDL_Rect ball;
        ball.x = ball_x - BALL_RADIUS;
        ball.y = ball_y - BALL_RADIUS;
        ball.w = BALL_RADIUS * 2;
        ball.h = BALL_RADIUS * 2;
        SDL_RenderFillRect(renderer, &ball);

        // 更新屏幕
        SDL_RenderPresent(renderer);

        // 如果小球超出屏幕，重置位置
        if (ball_x > SCREEN_WIDTH) {
            ball_x = BALL_RADIUS;
        }

        // 延迟 10 毫秒
        SDL_Delay(10);
    }

    // 释放资源
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}